const Router = require('koa-router');
const router = new Router();

router.get('/', async ctx => {
    const { getWorks } = require('../models/works');
    const works_res = await getWorks(ctx.access_token, ctx.query)
    ctx.errcode(works_res.data.errcode, works_res.data.errmsg)
    
    ctx.body = {
        code: 200,
        data: {
            ...works_res.data,
            data: works_res.data.data.map(item => JSON.parse(item)),
        },
        msg: 'ok'
    };
})
router.get('/:id', async ctx => {
    const { getInfo } = require('../models/works');
    const works_res = await getInfo(ctx.access_token, ctx.params.id)
    ctx.errcode(works_res.data.errcode, works_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: (works_res.data.data.map(item => JSON.parse(item)))[0],
        msg: 'ok'
    };
})
router.post('/', async ctx => {
    const { addWorks } = require('../models/works');
    const works_res = await addWorks(ctx.access_token, ctx.request.body)
    ctx.errcode(works_res.data.errcode, works_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: works_res.data,
        msg: 'ok'
    };
})
router.delete('/', async ctx => {
    const { delWorks } = require('../models/works');
    const works_res = await delWorks(ctx.access_token, ctx.query.id)
    ctx.errcode(works_res.data.errcode, works_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: works_res.data,
        msg: 'ok'
    };
})
router.put('/', async ctx => {
    const { updateWorks } = require('../models/works');
    const works_res = await updateWorks(ctx.access_token, ctx.request.body)
    console.log(works_res.data)
    ctx.errcode(works_res.data.errcode, works_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: works_res.data,
        msg: 'ok'
    };
})

module.exports = router.routes();